package com.quickcancellation.crm.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quickcancellation.crm.config.LogAspect;
import com.quickcancellation.crm.pojo.dto.PageDto;
import com.quickcancellation.crm.pojo.dto.PageParamsDto;
import com.quickcancellation.crm.pojo.dto.ResponseDto;
import com.quickcancellation.crm.pojo.entity.*;
import com.quickcancellation.crm.service.*;
import com.quickcancellation.crm.utils.DateUtils;
import com.quickcancellation.crm.utils.PageUtils;
import com.quickcancellation.crm.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 库存调拨申请表 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-03-14
 */


@RestController
@RequestMapping("/stockApply")
@CrossOrigin
@Api(tags = "用户管理")
@SaCheckLogin
@SaCheckRole("stockApply")
public class StoretransferController {


    @Resource
    private IStoretransferService stockTransferService;

    @Resource
    private HttpServletRequest request;

    @Resource
    private IUserinfoService userinfoService;

    @Resource
    private IStockService stockService;

   @Resource
   private IStockdetailService stockDetailService;


   @Resource
   private JdbcTemplate jdbcTemplate;

   @Resource
   private IDistributorService distributorService;

   @Resource
   private IProductService productService;

    @ApiOperation("审核申请列表查询")
    @PostMapping("/list")
    @LogAspect
    public ResponseDto stockTransferList(@RequestBody PageParamsDto<Map> params) {


        PageDto<Map> pageDto = PageUtils.getPageParams(params);


        List<Map> list = stockTransferService.getTransferList(pageDto);

        Integer count = stockTransferService.getTransferListCount(pageDto);

        return ResponseUtil.success(count, list);

    }

    @ApiOperation("发起审核")
    @PostMapping("/save")
    @LogAspect
    public ResponseDto save(@RequestBody Stocktransfer stocktransfer) {


        // 入出仓库不能相同
        if (Objects.equals(stocktransfer.getInDistributorId(), stocktransfer.getOutDistributorID())){
            return ResponseUtil.fail("调拨入出仓库不能相同!");
        }

        // 判断出库仓库库存是否够用
        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("productCode",stocktransfer.getProductCode());
        queryWrapper.eq("agDisId",stocktransfer.getOutDistributorID());
        queryWrapper.eq("agDisType",2);
        queryWrapper.select("stockBatch");
        Stock checkStock = stockService.getOne(queryWrapper);

        if (checkStock == null || checkStock.getStockBatch() - stocktransfer.getAmount() < 0){
            return ResponseUtil.fail("调拨出库仓库数量不足！");
        }


        // 获取当前申请人的id
        Userinfo userInfo = userinfoService.getUserInfoByRequest(request);

        String userId = userInfo.getId();

        stocktransfer.setCreateOp(userId);
        stocktransfer.setCreateTime(DateUtils.getNow());

        // 待审核
        stocktransfer.setAuditStatus(0);

        boolean result = stockTransferService.save(stocktransfer);

        return ResponseUtil.ok(result);
    }


    @ApiOperation("审核")
    @PostMapping("/audit")
    @LogAspect
    @Transactional
    public ResponseDto audit(@RequestBody Map<String,Object> params) {
        String userId = userinfoService.getUserInfoByRequest(request).getId();


        // 先判断权限
        boolean hasPermission = userinfoService.checkPermission(request, "仓库经理");
        if (!hasPermission){
            return ResponseUtil.fail("仓库经理才能审核");
        }
        Long auditId = MapUtils.getLong(params, "id");
        Integer auditStatus = MapUtils.getInteger(params, "auditStatus");
        String auditRemark = MapUtils.getString(params, "auditRemark");


        // 查询调拨记录信息
        QueryWrapper<Stocktransfer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",auditId);
        Stocktransfer stocktransfer = stockTransferService.getOne(queryWrapper);


        // 判断出库仓库库存是否够用
        QueryWrapper<Stock> stockQueryWrapper = new QueryWrapper<>();
        stockQueryWrapper.eq("productCode",stocktransfer.getProductCode());
        stockQueryWrapper.eq("agDisId",stocktransfer.getOutDistributorID());
        stockQueryWrapper.eq("agDisType",2);
        stockQueryWrapper.select("stockBatch");
        Stock stock = stockService.getOne(stockQueryWrapper);

        if (stock == null || stock.getStockBatch() - stocktransfer.getAmount() < 0){
            return ResponseUtil.fail("调拨出库仓库数量不足！");
        }
        Integer stockBatch = stock.getStockBatch();


        // 保存调拨审核信息
        stocktransfer.setAuditStatus(auditStatus);
        stocktransfer.setAuditReamrk(auditRemark);
        stocktransfer.setAuditTime(DateUtils.getNow());


        // 保存审核记录
        boolean result = stockTransferService.updateById(stocktransfer);

        if (auditStatus == 2 ){
            return ResponseUtil.ok(result);
        }


        if (!result){

            return ResponseUtil.fail("审核失败！");

        }

        // 添加调拨记录
        Stockdetail stockdetail = new Stockdetail();

        stockdetail.setType(1);
        stockdetail.setProductCode(stocktransfer.getProductCode());
        stockdetail.setSingleCount(0);
        stockdetail.setBatchCount(stocktransfer.getAmount());
        stockdetail.setCreateTime(DateUtils.getNow());
        stockdetail.setCreateOp(userId);

        stockdetail.setStockType(1);
        stockdetail.setRemark(auditRemark);
        stockdetail.setAuditType(1);
        stockdetail.setInDisAgId(stocktransfer.getInDistributorId());
        stockdetail.setOutDisAgId(stocktransfer.getOutDistributorID());
        boolean result2 = stockDetailService.save(stockdetail);

        if (!result2){
            return ResponseUtil.fail("调库失败！");
        }


        // 库存变动
        // 出库变动
        jdbcTemplate.update("update pd_t_stock set stockBatch = stockBatch - " + stockBatch + " where productCode = '" + stocktransfer.getProductCode() + "' and agDisId = '" + stockdetail.getOutDisAgId() + "'and agDisType = 2");


        // 入库变动
        QueryWrapper<Stock> stockCountQuery = new QueryWrapper<>();
        stockCountQuery.eq("productCode",stocktransfer.getProductCode());
        stockCountQuery.eq("agDisId",stockdetail.getInDisAgId());
        stockCountQuery.eq("agDisType",2);
        long count = stockService.count(stockCountQuery);
        if (count == 0){
            Stock newStock = new Stock();
            newStock.setStockBatch(stockBatch);
            newStock.setStockSingle(0);
            newStock.setProductCode(stocktransfer.getProductCode());
            newStock.setAgDisId(String.valueOf(stockdetail.getInDisAgId()));
            newStock.setAgDisType(2L);

        }else{
           jdbcTemplate.update("update pd_t_stock set stockBatch = stockBatch + " + stockBatch + " where productCode = '" + stocktransfer.getProductCode() + "' and agDisId = '" + stockdetail.getInDisAgId() + "'and agDisType = 2");
        }


        return ResponseUtil.success();
    }

    @ApiOperation("经销商列表")
    @PostMapping("/distributorList")
    @LogAspect
    public ResponseDto distributorList() {

        List<Distributor> list = distributorService.list();

        return ResponseUtil.success(list);
    }

    @ApiOperation("产品列表")
    @PostMapping("/productList")
    @LogAspect
    public ResponseDto productList() {

        List<Product> list = productService.list();

        return ResponseUtil.success(list);
    }


}
